from media.sensor import *
from media.display import *
from media.media import *
import image
import time,sys,os,utime

sensor_id=2

Max_Rect_Flag=False
Max_Rect_Corners=[[0,0] for i in range(4)]

def Find_Edge_Rect(img):
    global Max_Rect_Flag,Max_Rect_Corners
    # threshold 参数用于设置检测阈值(threshold大小和要检测矩形的像素大小有关，将阈值设定在要检测矩形的面积范围内可以减少外界其他噪声)
    # x_gradient 和 y_gradient 参数用于设置边缘梯度阈值（x_gradient 和 y_gradient越大识别越准确但耗费时间越长，x_gradient 和 y_gradient越小越快但干扰性大）
    Rects=img.find_rects(threshold = 50000, x_gradient=20, y_gradient=20)
    if Rects:
        Max_Rect=0
        for Rect in Rects:
            if(Rect.magnitude()>Max_Rect):
                Max_Rect_Flag=True
                Max_Rect=Rect.magnitude()
                Max_Rect_Corners=Rect.corners()


def DrawRects(img):
    if(Max_Rect_Flag==True):
        img.draw_line(Max_Rect_Corners[0][0],Max_Rect_Corners[0][1],Max_Rect_Corners[1][0],Max_Rect_Corners[1][1],color=(0,255,0),thickness=6)
        img.draw_line(Max_Rect_Corners[1][0],Max_Rect_Corners[1][1],Max_Rect_Corners[2][0],Max_Rect_Corners[2][1],color=(0,255,0),thickness=6)
        img.draw_line(Max_Rect_Corners[2][0],Max_Rect_Corners[2][1],Max_Rect_Corners[3][0],Max_Rect_Corners[3][1],color=(0,255,0),thickness=6)
        img.draw_line(Max_Rect_Corners[3][0],Max_Rect_Corners[3][1],Max_Rect_Corners[0][0],Max_Rect_Corners[0][1],color=(0,255,0),thickness=6)
    return img


# 显示模式选择：可以是 "VIRT"、"LCD" 或 "HDMI"
DISPLAY_MODE = "VIRT"

# 根据模式设置显示宽高
if DISPLAY_MODE == "VIRT":
    # 虚拟显示器模式
    DISPLAY_WIDTH = 800
    DISPLAY_HEIGHT = 480
elif DISPLAY_MODE == "LCD":
    # 3.1寸屏幕模式
    DISPLAY_WIDTH = 800
    DISPLAY_HEIGHT = 480
elif DISPLAY_MODE == "HDMI":
    # HDMI扩展板模式
    DISPLAY_WIDTH = 1920
    DISPLAY_HEIGHT = 1080
else:
    raise ValueError("未知的 DISPLAY_MODE，请选择 'VIRT', 'LCD' 或 'HDMI'")

def Display_Init():
    if DISPLAY_MODE == "VIRT":
        Display.init(Display.VIRT, width=DISPLAY_WIDTH, height=DISPLAY_HEIGHT, fps=30)
    elif DISPLAY_MODE == "LCD":
        Display.init(Display.ST7701,width=DISPLAY_WIDTH,height=DISPLAY_HEIGHT,to_ide=False)
    elif DISPLAY_MODE == "HDMI":
        Display.init(Display.LT9611, width=DISPLAY_WIDTH, height=DISPLAY_HEIGHT, to_ide=True)
    else:
        raise ValueError("未知的 DISPLAY_MODE，请选择 'VIRT', 'LCD' 或 'HDMI'")


try:
    #传感器初始化
    sensor=Sensor(id=sensor_id,width=DISPLAY_WIDTH,height=DISPLAY_HEIGHT)
    #复位
    sensor.reset()

    #设置输出尺寸和通道
    sensor.set_framesize(width=DISPLAY_WIDTH,height=DISPLAY_HEIGHT,chn=CAM_CHN_ID_1)
    #设置输出画面格式
    sensor.set_pixformat(Sensor.RGB565,CAM_CHN_ID_1)
    #是否水平翻转
    sensor.set_hmirror(False)
    #是否垂直翻转
    sensor.set_vflip(False)

    #显示设备初始化
    Display_Init()

    #媒体堆栈初始化
    MediaManager.init()

    sensor.run()

    #帧率显示对象初始化
    clock=utime.clock()

    while True:
        os.exitpoint()

        #更新当前时间
        clock.tick()

        #截取当前画面
        img=sensor.snapshot(CAM_CHN_ID_1)
        img=img.gaussian(1)

        Find_Edge_Rect(img)
        img=DrawRects(img)
        #显示当前画面
        Display.show_image(img)

        Max_Rect_Flag=False
        Max_Rect_Corners=[[0,0] for i in range(4)]

        print("fps: ",clock.fps())

except KeyboardInterrupt as e:
    print("用户停止: ", e)
except BaseException as e:
    print(f"异常: {e}")
finally:
    # 停止传感器运行
    if isinstance(sensor, Sensor):
        sensor.stop()
    # 反初始化显示模块
    Display.deinit()
    os.exitpoint(os.EXITPOINT_ENABLE_SLEEP)
    time.sleep_ms(100)
    # 释放媒体缓冲区
    MediaManager.deinit()

